package BeenChina.PM.Action;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray; 

import BeenChina.PM.Model.ModelTimeREntryTime;
import BeenChina.PM.Model.ModelTimeRUtilization;
import BeenChina.PM.Model.ModelUser;
import BeenChina.PM.Service.ServiceFactory;
import BeenChina.PM.Util.EncodeDownLoadFileName;
import BeenChina.PM.Util.ExportInfo;
import BeenChina.PM.Util.ExportToExcel;
import BeenChina.PM.Util.StringUtil;
import BeenChina.PM.Util.xmlSerializer;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
 
public class TimeRUtilizationQueryAction extends ActionSupport
{   
 
	private static final long serialVersionUID = 1L;
	private String dateFrom;
	private List<ModelTimeRUtilization> timeRUtilizations = new ArrayList<ModelTimeRUtilization>();
	private List<ModelTimeREntryTime> timeREntryTimes = new ArrayList<ModelTimeREntryTime>();
	private Map<String, Object> chartData; 
	private DecimalFormat df = new DecimalFormat("#.0"); 
	private InputStream excelStream;  
	private String fileName;
	private static String EXPORTID = "451";
	private boolean exportExcel; 
	private static final Log log = LogFactory.getLog(TimeRUtilizationQueryAction.class);
	
	public boolean isExportExcel() {
		return exportExcel;
	} 

	 
	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getFileName() throws UnsupportedEncodingException {		
		ServletActionContext.getResponse().setHeader("charset","UTF-8");
		fileName = EncodeDownLoadFileName.encode(ServletActionContext.getRequest(), fileName); 
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public Map<String, Object> getChartData() {
		return chartData;
	} 
	 

	public String getDateFrom() {
		return dateFrom;
	} 

	public void setDateFrom(String dateFrom) {
		this.dateFrom = dateFrom;
	}




	@Override
	public String execute()	{	
		ModelUser user = (ModelUser) ActionContext.getContext().getSession().get("user");
		if (user!=null)
		  exportExcel = user.concatPermission(EXPORTID);
  		return "load";
	}
	
	public List<ModelTimeRUtilization> getTimeRUtilizations() {
		return timeRUtilizations;
	}

	public List<ModelTimeRUtilization> getData()	throws Exception {
		try{
			 if (StringUtil.isDate(dateFrom))  
			 {
				 timeRUtilizations = ServiceFactory.getInstance().getCaseProductionInfoService().selectTimeRUtilization(dateFrom);			 				
				 return timeRUtilizations;	 
			 }
			 else {
				 return null;
			}
			 
		 }
		 catch(Exception exp){
			 throw exp;
		 }
		
	}
	public List<ModelTimeREntryTime> getDetailData()	throws Exception {
		try{
			 if (StringUtil.isDate(dateFrom))  
			 {
				 timeREntryTimes= ServiceFactory.getInstance().getCaseProductionInfoService().selectTimeREntryTime(dateFrom)	;			 				
				 return timeREntryTimes;	 
			 }
			 else {
				 return null;
			}
			 
		 }
		 catch(Exception exp){
			 throw exp;
		 }
		
	}
	
	 public String refreshChartData() throws Exception
	 { 
		 JSONArray mapSdTime = new JSONArray();
		 JSONArray mapLdTime = new JSONArray();
		 JSONArray mapTotalTime = new JSONArray();
		 JSONArray mapWorkTime = new JSONArray();
		 JSONArray mapNoWorkTime = new JSONArray();
		 JSONArray mapUtilization = new JSONArray();
		 
 
		 
		 getData();
		 
		 
		 if (timeRUtilizations !=null && timeRUtilizations.size()>0)
		 {
			for (ModelTimeRUtilization model : timeRUtilizations) {
				
				JSONArray json = new JSONArray();
				json.add(model.getHour() );
				json.add(model.getSdTime()==null ? 0 : model.getSdTime());
				mapSdTime.add(json);
				
				json = new JSONArray();				
				json.add(model.getHour() );
				json.add(model.getLdTime()==null ? 0 : model.getLdTime());
				mapLdTime.add(json);
				
				
				json = new JSONArray();				
				json.add(model.getHour() );
				json.add(model.getTotalTime()==null ? 0 : model.getTotalTime());
				mapTotalTime.add(json);
				
				
				Double wTime= model.getWorkTime()==null ? 0 : model.getWorkTime();
				json = new JSONArray();				
				json.add(model.getHour() );
				json.add(wTime);
				mapWorkTime.add(json);
				
				Double nwTime =model.getNoWorkTime()==null ? 0 : model.getNoWorkTime();
				json = new JSONArray();				
				json.add(model.getHour() );
				json.add(nwTime);
				mapNoWorkTime.add(json);
				
 
				
				
 
				
			}
		 }
		 
		 Map<String, Object> map = new HashMap<String, Object>();  
	     map.put("SdTime", mapSdTime);  	     	     
		 map.put("LdTime", mapLdTime); 
		 map.put("TotalTime", mapTotalTime);
		 map.put("WorkTime", mapWorkTime);
		 map.put("Utilization", mapUtilization);
		 map.put("NoWorkTime", mapNoWorkTime);
		 
 
		 
		 
		 map.put("Table", getMasterTable(this.timeRUtilizations));
		 getDetailData();
		 map.put("TableDetail", getDetailTable(this.timeREntryTimes));  	
		 
		 chartData = map;
	     return Action.SUCCESS;  
	 }
	 public JSONArray getMasterTable(List<ModelTimeRUtilization> list) throws Exception
	 {
 
		 
		 JSONArray mapMasterTable = new JSONArray();
		 if (timeRUtilizations ==null || timeRUtilizations.size() ==0)
		 {
			 return mapMasterTable;
		 }
		 
		 Double totalSum,WorkSum;
		 
		 //init head
		 JSONArray json = new JSONArray();		 
		 //init table head
		 json.add("時間帯(CST)");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(model.getHour());
		}
		 json.add("合計");
		 mapMasterTable.add(json);
		 
		 
		 //result
		 Double sumDouble=0.0;
		 json = new JSONArray();		 
		 //init table head
		 json.add("長納期対応");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(df.format(model.getLdTime()));
		  sumDouble += model.getLdTime();
		}
		 json.add(df.format(sumDouble));
		 mapMasterTable.add(json);

		 json = new JSONArray();		 
		 sumDouble=0.0;
		 json.add("短納期対応");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(df.format(model.getSdTime()));
		  sumDouble += model.getSdTime();
		}
		 json.add(df.format(sumDouble));
		 mapMasterTable.add(json);
		 
		 json = new JSONArray();		 
		 sumDouble=0.0;
		 json.add("総稼動");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(df.format(model.getTotalTime()));
		  sumDouble += model.getTotalTime();
		}
		 json.add(df.format(sumDouble));
		 mapMasterTable.add(json);
		 totalSum = sumDouble;
		 
		 json = new JSONArray();		 
		 sumDouble=0.0;
		 json.add("実際総出勤");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(df.format(model.getWorkTime()));
		  sumDouble += model.getWorkTime();
		}
		 json.add(df.format(sumDouble));
		 mapMasterTable.add(json);
		 WorkSum = sumDouble;
		 
		 json = new JSONArray();		 
		 sumDouble=0.0;
		 json.add("非稼働");
		 for (ModelTimeRUtilization model : list) { 
		  json.add(df.format(model.getNoWorkTime()));
		  sumDouble += model.getNoWorkTime();
		}
		 json.add(df.format(sumDouble));
		 mapMasterTable.add(json);

		 
		 json = new JSONArray();		 
		 sumDouble=0.0;
		 json.add("実稼働率");
		 // 総稼動 /	 実際総出勤

		 for (ModelTimeRUtilization model : list) { 
		  json.add(model.getUtilization());		  
		}
		 String temp = df.format(totalSum/WorkSum * 100) + '%';
		 json.add(temp);
		 mapMasterTable.add(json);
		 
		 return mapMasterTable;
	 }
	 
	 public JSONArray getDetailTable(List<ModelTimeREntryTime> list) throws Exception
	 {
	 
		 
		 JSONArray mapDetailTable = new JSONArray();
		 if (timeREntryTimes ==null || timeREntryTimes.size() ==0)
		 {
			 return mapDetailTable;
		 }
		 
		 //folder
		 JSONArray jsonFolder = new JSONArray();		 
		 //init table folder
		 jsonFolder.add("合計");
		 jsonFolder.add("-");
		 jsonFolder.add("-");
		 jsonFolder.add("-");
		 
		 JSONArray json = new JSONArray();		 
		 //init table head
		 json.add("No.");
		 json.add("案件");
		 json.add("納期");
		 json.add("類別");
		 
		 String firstday = timeREntryTimes.get(0).getHour();
		 
		 Double sumday = 0.0;
		 
		 for (ModelTimeREntryTime model : list) {
			 String nextday = model.getHour();
			 if (!nextday.equals(firstday))
			{
		  	   jsonFolder.add(df.format(sumday));
		  	   json.add(firstday);		 
				 
				firstday = nextday;
				sumday = model.getEntryTime();
				//json.add(nextday.substring(6,10));
			}
			 else {
				sumday += model.getEntryTime();
			}
		}
	 	// add last item
		 jsonFolder.add(df.format(sumday));
		 json.add(firstday);
		 
		 mapDetailTable.add(json);
		 
		 //init result head
		 firstday = list.get(0).getDate();
		 List<ModelTimeREntryTime> resultHeader = new ArrayList<ModelTimeREntryTime>();
		 for (int i = 0; i < list.size(); i++) {
			 ModelTimeREntryTime model = list.get(i);
			 
			  if (model.getDate().equals(firstday))
			  {
				  resultHeader.add(model);
			  }
		}
		 for (int i = 0; i < resultHeader.size(); i++) {
			 ModelTimeREntryTime modelH = resultHeader.get(i);
			 
			 json = new JSONArray();	
			 
			 json.add( i+1 );
			 json.add(modelH.getCaseName());
			 json.add(modelH.getDeliveryTime());
			 json.add(modelH.getDeliveryType());
			 
			 for (int j = 0; j < list.size(); j++) {
				 ModelTimeREntryTime model = list.get(j); 
				 
				 if ( modelH.getCaseName().equals(model.getCaseName()) &&
					  modelH.getDeliveryTime().equals(model.getDeliveryTime()) &&
					  modelH.getDeliveryType().equals(model.getDeliveryType())
						 )
				 {
					 Double entryTime = model.getEntryTime()==null ? 0 : model.getEntryTime();
					 json.add( df.format(entryTime) );
				 }
			}
			 
			 mapDetailTable.add(json);
		}
		 
	
		 
		 mapDetailTable.add(jsonFolder);
		 return mapDetailTable;
	 }
		public String export() throws Exception{		 
			try{	  
					 
				String file=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/TimeRUtilizationQuery.xls");
				
				 getData();
				 getDetailData(); 
				 Map<String, JSONArray> map = new HashMap<String, JSONArray>();   
				
				 map.put("基礎情報", getMasterTable(this.timeRUtilizations));  
				 map.put("案件稼動状況明細 ", getDetailTable(this.timeREntryTimes)); 
				
				
				ByteArrayOutputStream out = new ByteArrayOutputStream(); 		
				this.setFileName("実稼働状況集計・日集計_" + this.dateFrom);			
				String infoFile=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/TimeRUtilizationQuery.xml");
				List<ExportInfo> infoList = (new xmlSerializer<List<ExportInfo>>()).read(infoFile);
				
				ExportToExcel.export(file, map, infoList,out);
				
				setExcelStream(new ByteArrayInputStream(out.toByteArray()));	   			   			      
				out.close();
			
				return ActionSupport.SUCCESS;
			}
			catch(Exception exp){
				
				log.error(exp);
				return ActionSupport.ERROR;
			}		
		}		
}
